package com.hua.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.mapper.UserMapper;
import com.hua.pojo.Invite;
import com.hua.pojo.User;
import com.hua.pojo.UserInfo;
import com.hua.pojo.UserRole;
import com.hua.pojo.securityUser.SecurityUser;
import com.hua.service.InviteService;
import com.hua.service.UserInfoService;
import com.hua.service.UserRoleService;
import com.hua.service.UserService;
import com.hua.utils.HuaUtil;
import com.hua.vo.RegisterFrom;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author ONE-X
 * @date 2020/11/09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserDetailsService, UserService {

	static Logger logger = Logger.getRootLogger();

	@Autowired
	UserService userService;

	@Autowired
	UserRoleService userRoleService;

	@Autowired
	InviteService inviteService;

	@Autowired
	HttpSession session;

	@Autowired
	UserInfoService userInfoService;


	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		User user = userService.getOne(new QueryWrapper<User>().eq("username", s));
		if(user == null){
			logger.info("=====> 不存在该用户\t"+s);
			throw new UsernameNotFoundException(s+"\t不存在");
		}
		// 将信息存入session
		session.setAttribute("loginUser",user);

		// 获取他的权限

		// 数据库里的密码是以及加密过的信息
		return new SecurityUser(user.getUsername(),user.getPassword(),getGrantedAuthority(user.getRoleId()),user.getUid());
	}

	public List<GrantedAuthority> getGrantedAuthority(int id){
		UserRole userRole = userRoleService.getById(id);
		List<GrantedAuthority> list = new ArrayList<>();
		list.add(new SimpleGrantedAuthority(userRole.getName()));
		return list;
	}

	// 注册用户
	@Override
	public void registerUser(RegisterFrom registerFrom){
		// 先注册用户
		User user = new User();
		String uuid = HuaUtil.getUuid();
		user.setUid(uuid);
		user.setRoleId(2);
		user.setPassword(new BCryptPasswordEncoder().encode(registerFrom.getPassword()));
		// 头像默认
		user.setAvatar("/headImg/"+uuid+".jpg");
		// 用户名称
		user.setUsername(registerFrom.getUsername());
		// 登录时间
		user.setLoginDate(HuaUtil.DATE);
		// 注册时间
		user.setGmtCreate(HuaUtil.DATE);
		userService.save(user);
		// 注册用户初始化信息
		UserInfo userInfo = new UserInfo();
		userInfo.setUid(uuid);
		// 昵称默认为自己的用户名
		userInfo.setNickname(registerFrom.getUsername());
		userInfoService.save(userInfo);


		// 获取ks_invite
		Invite invite = inviteService.getOne(new QueryWrapper<Invite>().eq("code", registerFrom.getCode()).eq("status", "0"));
		if(invite.getStatus() != 0){
			logger.error(HuaUtil.DATE+" 验证码被抢先注册");
			throw new NullPointerException();
		}
		invite.setUid(uuid);
		// 已经被注册
		invite.setStatus(1);
		// 激活时间
		invite.setActiveTime(HuaUtil.DATE);
		inviteService.updateById(invite);

	}
}
